﻿using System;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.DBM;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.IDAL;
using KPIS.GERP.GFMS.MODEL;
using Telerik.Web.UI;
using SystemInfo = KPIS.GERP.GFMS.MODEL.SystemInfo;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_Payments : System.Web.UI.Page
    {
        Main main = new Main();
        IBLL_FIM_Payments pay = new B_FIM_Payments();
        IBLL_FIM_PaymentCheques paycheque = new B_FIM_PaymentCheques();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_HRM_MP_WorkAreas area = new B_HRM_MP_WorkAreas();
        B_MessageSend send = new B_MessageSend();
        IBLL_FIM_MAS_Events ev = new B_FIM_MAS_Events();
        IBLL_BGM_ProjectOperation oper = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationReport operRpt = new B_BGM_ProjectOperationReport();
        IBLL_FIM_SystemControls sc = new B_FIM_SystemControls();
        IBLL_HRM_PR_PayrollDtls prd = new B_HRM_PR_PayrollDtls();
        IBLL_FIM_MAS_ExpenseRates rate = new B_FIM_MAS_ExpenseRates();
        IBLL_FIM_MAS_Methods met = new B_FIM_MAS_Methods();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_Cheques cheque = new B_FIM_Cheques();
        IBLL_HRM_PS_Employees emplist = new B_HRM_PS_Employees();
        IBLL_HRM_PS_EMP_BOOK_BANKS emp_acc = new B_HRM_PS_EMP_BOOK_BANKS();
        IBLL_ICM_MasContactBank con_acc = new B_ICM_MasContactBank();
        IBLL_FIM_Payroll prl = new B_FIM_Payroll();
        IBLL_ACM_GENERATE_ACCOUNT_Auto acm = new B_ACM_GENERATE_ACCOUNT_Auto();
        IDAL_ACM_GENERATE_ACCOUNT_Auto acm2 = new D_ACM_GENERATE_ACCOUNT_Auto();
        IBLL_CodeGenerate cg = new B_CodeGenerate();
        IBLL_FIM_Transfers transfer = new B_FIM_Transfers();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //======= test only =========
                //Session["EmpSeq"] = "1";
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();

                //===========================

                LoadDDLFilterEventSeq();
                LoadDDLFilterBgmSourceSeq();
                LoadDDLFilterWorkAreaSeq();
                LoadRblMethodSeq();
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
                //LoadDDLBankAccSeq();
                //ddlBankAccSeq_SelectedIndexChanged(null, null);
                //LoadDDLChequeSeq();
                LoadDDLFromBankAccSeq();
                LoadDDLToBankAccSeq(null);
                LoadDDLToContactBankAccSeq(null);
                ViewState["_tmpConId"] = null;
                ViewState["_tmpEmpSeq"] = null;
                rblMethodSeq_SelectedIndexChanged(null, null);

                if (Request["menu_payments"] == "history")
                {
                    cmdHistory_Click(null, null);
                }
                else { 
                    cmdArival_Click(null, null);
                }
            }
        }

        protected void LoadRadGrid1()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strEventSeq = ddlFilterEventSeq.SelectedValue;
            string strContactSeq = null;
            //string strEmpSeq = Session["EmpSeq"].ToString();
            RadGrid1.DataSource = mr.GetFull(strBgmSourceSeq, strBgmYear, strWorkAreaSeq, strEventSeq
                , strContactSeq, null, null, true);
        }

        protected void LoadRadGrid2()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strEventSeq = ddlFilterEventSeq.SelectedValue;
            string strEmpSeq = Session["EmpSeq"].ToString();
            var dataSource = pay.GetFull(strBgmSourceSeq, strBgmYear, strWorkAreaSeq, strEventSeq, "0");
            dataSource = dataSource.Where(m => m.event_seq != 27).ToList();
            bool loadOnlyApproved = cmdMultiSelectStop.Visible && pnlMultiApprove1.Visible;

            if (!loadOnlyApproved)
            {
                RadGrid2.DataSource = dataSource;
            }
            else
            {
                RadGrid2.DataSource = dataSource.Where(o => o.record_status_name == "อนุมัติแล้ว");
            }
        }
        protected void LoadData(string strMoneyReqSeq, string strPaySeq)
        {
            M_FIM_MoneyRequests reqInfo = null;
            M_FIM_Payments payInfo = null;

            if (!string.IsNullOrEmpty(strMoneyReqSeq))
            {
                reqInfo = mr.GetInfo(strMoneyReqSeq);
                //M_FIM_Payments payInfo = string.IsNullOrEmpty(strPaySeq) ? null : pay.GetInfo(strPaySeq);

                lblEventName.Text = reqInfo.event_name;
                lblMoneyReqSeq.Text = reqInfo.money_req_seq.ToString();
                lblReqRefNo.Text = reqInfo.ref_no;
                lblMoneyReqName.Text = reqInfo.money_req_name;
                lblBgmProjOperCode.Text = reqInfo.bgm_proj_oper_code;
                lblBgmProjOperName.Text = reqInfo.bgm_proj_oper_name;
                lblBgmExpGrpName.Text = reqInfo.bgm_exp_grp_name;
                lblReqEmpName.Text = reqInfo.emp_name;
                lblPayeeName.Text = reqInfo.payee_name;
                lblEventSeq.Text = reqInfo.event_seq.ToString();
                lblEmpSeq.Text = reqInfo.emp_seq.ToString();
                lblContactSeq.Text = reqInfo.contact_seq.ToString();
                lblPetitionSeq.Text = reqInfo.petition_seq.ToString();
                lblPetitionDtlsSeq.Text = reqInfo.petition_dtls_seq.ToString();
                lblPetitionNo.Text = reqInfo.petition_no;
                lblPetitionRefNo.Text = reqInfo.petition_ref_no;
                lblReqBathAmount.Text = (reqInfo.total_amount ?? 0).ToString("#,##0.00");
                tblAdvance.Visible = string.IsNullOrEmpty(reqInfo.use_advance) ? false : reqInfo.use_advance == "1";
                double amountDeduction = (double)prl.GetPayrollDeductions(null, null, reqInfo.ref_no).Sum(o => o.amount);

                if (reqInfo != null)
                {
                    LoadGrdMoneyRequestDtls(strMoneyReqSeq);
                }

                if (!String.IsNullOrEmpty(lblContactSeq.Text))
                {
                    ViewState["_tmpConId"] = lblContactSeq.Text;
                    ViewState["_tmpEmpSeq"] = null;
                }
                else
                {
                    ViewState["_tmpEmpSeq"] = lblEmpSeq.Text;
                    ViewState["_tmpConId"] = null;
                }

                divMoneyRequest.Visible = true;
            }
            else
            {
                divMoneyRequest.Visible = false;
            }

            if (string.IsNullOrEmpty(strPaySeq))
            {
                lblPaySeq.Text = "";
                lblPayRefNo.Text = "";
                txtPayName.Text = "จ่าย" + lblMoneyReqName.Text;
                txtTaxRate.Text = "0";
                txtAmountTax.Text = "0";
                //txtTaxInvoiceId.Text = "";
                dpPayDate.SetValue(DateTime.Today);
                //dpTaxInvoiceDate.SetValue(null);
                rblMethodSeq.SelectedValue = "2";
                PanelCheque.Visible = true;
                PanelTranfer.Visible = false;
            }
            else
            {
                payInfo = pay.GetInfo(strPaySeq);
                lblAmountVat.Text = (payInfo.vat ?? 0).ToString("#,##0.00");
                txtTaxRate.Text = (payInfo.tax_rate ?? 0).ToString("#,##0.00");
                txtAmountTax.Text = (payInfo.tax ?? 0).ToString("#,##0.00");
                lblPenalty.Text = (payInfo.penalty_amount ?? 0).ToString("#,##0.00");
                lblEventSeq.Text = payInfo.event_seq.ToString();
                lblEventName.Text = payInfo.event_name;
                lblPayAmount.Text = (payInfo.amount ?? 0).ToString("#,##0.00");

                var dExcludeVatAmount = reqInfo != null ? Math.Round((reqInfo.total_amount ?? 0)*(100/(100 + (payInfo.vat_rate ?? 0))), 2) : 0;
                lblPaySeq.Text = strPaySeq;
                lblPayRefNo.Text = payInfo.ref_no;
                dpPayDate.SetValue(payInfo.pay_date.Value);
                txtPayName.Text = payInfo.pay_name;
                rblMethodSeq.SelectedValue = payInfo.method_seq.ToString();
                lblContactSeq.Text = payInfo.contact_seq.ToString();
                //dpTaxInvoiceDate.SetValue(payInfo.tax_invoice_date);
                //txtTaxInvoiceId.Text = payInfo.tax_invoice_id;
               
                if (rblMethodSeq.SelectedValue.Equals("2"))
                {
                    ddlFromBankAcc.SelectedValue = payInfo.from_bank_acc_id.ToString();
                    ddlToBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
                }
                else if (rblMethodSeq.SelectedValue.Equals("3"))
                {
                    ddlToBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
                }
            }

            if (PanelCheque.Visible)
            {
                LoadDDLBankAccSeq();
                //ddlBankAccSeq_SelectedIndexChanged(null, null);
                LoadDataCheque();
                //txtActualPayDate.SetValue(null);
                //dpChequePayDate.SetValue(null);
                //dpChequeDate2.SetValue(DateTime.Today);
                //dpChequeDate.SetValue(DateTime.Today);
                cmdAddNew.Visible = cmdAddNew.Visible = (cmdInsert1.Visible || cmdUpdate1.Visible);
                PanelEditCheque.Visible = false;
                cmdInsert2.Visible = true;
                cmdUpdate2.Visible = false;
                cmdDelete2.Visible = false;
                cmdCancel2.Visible = true;
                PanelTranfer.Visible = false;
            }
            
            //if(reqInfo.event_seq == 14)
            //{
            //    PanelPayrollDeduction.Visible = true;
            //    LoadDataPayrollDeduction(reqInfo.ref_no);
            //}
        }

        protected void LoadGrdMoneyRequestDtls(string strMoneyReqSeq)
        {
            grdMoneyRequestDtls.DataSource = mrd.GetFull(strMoneyReqSeq);
            grdMoneyRequestDtls.DataBind();

            SumAmount();
        }

        protected void LoadDataCheque()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ViewState["Cheque"] = paycheque.GetFull("-1", null);
            }
            else
            {
                ViewState["Cheque"] = paycheque.GetFull(lblPaySeq.Text, null);
            }

            grdCheque.DataSource = (IList<M_FIM_PaymentCheques>) ViewState["Cheque"];
            grdCheque.DataBind();
        }

        protected void LoadDataPayrollDeduction(string ref_no)
        {
            var payrollDeduction = prl.GetPayrollDeductions(null, null, ref_no);
            rpeDeductionIndex.DataSource = payrollDeduction;
            rpeDeductionIndex.DataBind();
        }

        protected void LoadDDLFilterEventSeq()
        {
            ddlFilterEventSeq.DataSource = ev.GetList();
            ddlFilterEventSeq.DataBind();

            main.InsertEmptyDDLAll(ddlFilterEventSeq);
            ddlFilterEventSeq.SelectedIndex = 0;
        }

        protected void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();

            ddlFilterBgmSourceSeq.SelectedIndex = 0;
        }

        protected void LoadDDLFilterWorkAreaSeq()
        {
            ddlFilterWorkAreaSeq.DataSource = area.GetFull();
            ddlFilterWorkAreaSeq.DataBind();
            main.InsertEmptyDDLAll(ddlFilterWorkAreaSeq);

            ddlFilterWorkAreaSeq.SelectedIndex = 0;
        }

        protected void LoadRblMethodSeq()
        {
            rblMethodSeq.DataSource = met.GetList();
            rblMethodSeq.DataBind();

            // ddlFilterWorkAreaSeq.SelectedIndex = 1; #edit because สรพ. has workarea = null as default
        }

        protected void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList("2", ddlFilterBgmSourceSeq.SelectedValue, null, null, tblAdvance.Visible);
            ddlBankAccSeq.DataBind();

            ddlBankAccSeq.SelectedIndex = 0;
            LoadDDLChequeSeq();
        }

        protected void LoadDDLFromBankAccSeq()
        {
            ddlFromBankAcc.DataSource = acc.GetList(null, ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlFromBankAcc.DataBind();
            //main.InsertEmptyDDLSelect(ddlFromBankAcc);
            ddlFromBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLToBankAccSeq(int? emp_seq)
        {
            ddlToBankAcc.Text = "";
            ddlToBankAcc.DataSource = emp_acc.GetList(emp_seq);
            ddlToBankAcc.DataBind();
           // main.InsertEmptyDDLSelect(ddlToBankAcc);
            ddlToBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLToContactBankAccSeq(int? ConId)
        {
            ddlToConBankAcc.Text = "";
            ddlToConBankAcc.DataSource = con_acc.GetList(ConId);
            ddlToConBankAcc.DataBind();
            //main.InsertEmptyDDLSelect(ddlToConBankAcc);
            ddlToConBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLChequeSeq()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, null, null, "1");
            }
            else
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, lblPaySeq.Text, null, "1");
            }
            ddlChequeSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlChequeSeq);
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected bool CheckData1()
        {
            bool bOK = true;
            string strError = "";

            if (dpPayDate.GetStringValue().Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("วันที่ทำรายการ");
            }
            else if (txtPayName.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ชื่อรายการจ่ายเงิน");
            }

            if (rblMethodSeq.SelectedIndex.Equals(2))
            {
                if (String.IsNullOrEmpty(ddlFromBankAcc.SelectedValue))
                {
                    bOK = false;
                    strError = main.ErrorEmpty("บัญชีโอน");
                }                
            }

            if (rblMethodSeq.SelectedIndex.Equals(2) || rblMethodSeq.SelectedIndex.Equals(3))
            {
                if (ViewState["_tmpConId"] != null)
                {
                    if (String.IsNullOrEmpty(ddlToConBankAcc.SelectedValue))
                    {
                        bOK = false;
                        strError = main.ErrorEmpty("บัญชีรับ");
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(ddlToBankAcc.SelectedValue))
                    {
                        bOK = false;
                        strError = main.ErrorEmpty("บัญชีรับ");
                    }
                }
            }


            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckData2()
        {
            bool bOK = true;
            string strError = "";

            if (ddlBankAccSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("บัญชีเงินฝาก");
            }
            else if (ddlChequeSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("เช็คเลขที่");
            }
            else if (txtChequeAmount.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จำนวนเงิน");
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        //============================ control events ==============================

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick")
            {
                GridDataItem item = (GridDataItem) e.Item;

                PanelEdit1.Visible = true;
                PanelView.Visible = false;
                cmdInsert1.Visible = true;
                cmdUpdate1.Visible = false;
                cmdDelete1.Visible = false;
                cmdApprove.Visible = false;
                cmdReject.Visible = true;
                cmdRealPay.Visible = false;
                PanelMessageSend.Visible = false;
                divControl1.Visible = true;
                rblMethodSeq.Enabled = true;

                lblRecordStatus.Text = "W";
                LoadData(main.WebString(item["money_req_seq"].Text), "");
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid1();
            }
        }

        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick")
            {
                GridDataItem item = (GridDataItem) e.Item;
                string strRecordStatus = pay.GetInfo(main.WebString(item["pay_seq"].Text)).record_status;
                lblRecordStatus.Text = strRecordStatus;
                bool bApproved = strRecordStatus == "A";

                PanelEdit1.Visible = true;
                PanelView.Visible = false;
                cmdInsert1.Visible = false;
                cmdUpdate1.Visible = !bApproved;
                cmdDelete1.Visible = !bApproved;
                //cmdCancel2.Visible = true;
                cmdAddNew.Visible = !bApproved;
                cmdApprove.Visible = true;
                cmdReject.Visible = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                cmdApprove.Enabled = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                cmdRealPay.Visible = strRecordStatus == "A" && main.WebString(item["real_pay_date"].Text).Length == 0
                    && (main.WebString(item["method_seq"].Text) == "1" || main.WebString(item["method_seq"].Text) == "3");
                PanelMessageSend.Visible = false;
                divControl1.Visible = true;
                LoadData(main.WebString(item["money_req_seq"].Text), main.WebString(item["pay_seq"].Text));
                rblMethodSeq_SelectedIndexChanged(null, null);
                if (strRecordStatus == "A")
                    rblMethodSeq.Enabled = false;
                else 
                    rblMethodSeq.Enabled = true;
               
                ddlFromBankAcc.SelectedValue = item["from_bank_acc_id"].Text;
                if (item["contact_seq"].Text.Length > 0) ddlToConBankAcc.SelectedValue = item["to_bank_acc_id"].Text;
                else ddlToBankAcc.SelectedValue = item["to_bank_acc_id"].Text;

                rblMethodSeq.Enabled = false;
                PanelEditCheque.Visible = false;
                PanelPayCheque.Visible = false;

                //if (bApproved && main.WebString(item["method_seq"].Text) == "2")
                //{
                //    postFimTranfers(main.WebString(item["pay_seq"].Text),
                //                    pay.GetInfo(main.WebString(item["pay_seq"].Text)).bgm_source_seq.ToString(),
                //                    pay.GetInfo(main.WebString(item["pay_seq"].Text)).bgm_year.ToString());
                //}

                }
            // RadGrid2AfterBind();

            }

        protected void RadGrid2_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid2();
            }
        }

        protected void grdCheque_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                GridDataItem item = (GridDataItem) e.Item;

                PanelEditCheque.Visible = true;
                cmdAddNew.Visible = false;
                cmdInsert2.Visible = false;
                cmdUpdate2.Visible = cmdUpdate1.Visible;
                cmdDelete2.Visible = cmdUpdate1.Visible;
                cmdCancel2.Visible = true;

                lblPayChequeSeq.Text = main.WebString(item["pay_cheque_seq"].Text);
                ddlBankAccSeq.SelectedValue = main.WebString(item["bank_acc_seq"].Text);
                LoadDDLChequeSeq();
                ddlChequeSeq.SelectedValue = main.WebString(item["cheque_seq"].Text);
                txtChequeAmount.Text = main.WebString(item["amount"].Text);
                lblIndex.Text = item.ItemIndex.ToString();
            }
            else if (e.CommandName == "cmdPayCheque")
            {
                PanelPayCheque.Visible = true;

                GridDataItem item = (GridDataItem) e.Item;
                M_FIM_Cheques model = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));
                bool bAcmTransactionExist = acm2.CheckTransactionExist(lblPayRefNo.Text, "P");
                bool bAcmTransactionExist2 = acm2.CheckTransactionExist("CH" + model.cheque_no.ToString(), "G");
                ((HtmlInputText)dpChequePayDate.FindControl("txtDate")).Disabled = bAcmTransactionExist;

                lblChequeSeq.Text = model.cheque_seq.ToString();
                lblChequeBookSeq.Text = model.cheque_book_seq.ToString();
                lblChequeNo.Text = model.cheque_no.ToString();
                lblBankAccSeq.Text = model.bank_acc_seq.ToString();
                dpChequePayDate.SetValue(model.pay_date);
                dpChequeDate.SetValue(model.cheque_date);
                txtReceiver.Text = model.receiver;
                rblChequeStatus.SelectedValue = model.cheque_status;
                rblChequeStatus_SelectedIndexChanged(null, null);
                txtActualPayDate.SetValue(model.pay_date);
               // txtChequeRemarks.Text = model.cheque_remarks;
            }
        }

        protected void grdCheque_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataItem = (GridDataItem) e.Item;
                string ChequeStatus = main.WebString(dataItem["cheque_status"].Text);

                ((LinkButton) e.Item.FindControl("cmdEdit")).Visible = lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";
                ((Button) e.Item.FindControl("cmdPayCheque")).Visible = (ChequeStatus == "1" || ChequeStatus == "2"); // && lblRecordStatus.Text == "A";
            }
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = true;

            cmdAddNew.Visible = false;
            cmdDelete2.Visible = false;
            cmdInsert2.Visible = (cmdUpdate1.Visible || cmdInsert1.Visible);
            cmdUpdate2.Visible = false;
            divControl1.Visible = false;

            ddlChequeSeq.SelectedIndex = 0;
            txtChequeAmount.Text = lblPayAmount.Text;
            //txtTaxRate.Text = "0";
            //txtAmountTax.Text = "0";
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            string strPaySeq = lblPaySeq.Text;

            M_FIM_Payments info = new M_FIM_Payments();
            info.pay_seq = Convert.ToInt32(strPaySeq);
            info.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
            info.updated_when = DateTime.Now;

            pay.Delete(info);

            PanelEdit1.Visible = false;
            PanelView.Visible = true;
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            if (!CheckData1())
            {
                return;
            }

            M_FIM_Payments info = new M_FIM_Payments();

            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = lblEventSeq.Text;
            string strPayName = txtPayName.Text;
            string strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq == "1" ? "1" : "2");
            DateTime strPayDate = dpPayDate.GetDateValue().Value;
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strEmpSeq = (lblEmpSeq.Text.Length > 0 ? lblEmpSeq.Text : null);
            string strContactSeq = (lblContactSeq.Text.Length > 0 ? lblContactSeq.Text : null);
            string strContactPersonSeq = (lblContactPersonSeq.Text.Length > 0 ? lblContactPersonSeq.Text : null);
            string strPetitionSeq = (lblPetitionSeq.Text.Length > 0 ? lblPetitionSeq.Text : null);
            string strPetitionDtlsSeq = (lblPetitionDtlsSeq.Text.Length > 0 ? lblPetitionDtlsSeq.Text : null);
            string strAmount = lblPayAmount.Text; //(PanelPayrollDeduction.Visible ? lblPayAmountExcludeDeduction.Text : lblPayAmount.Text);
            //string strVatPercent = txtVatPercent.Text;
            //string strTaxPercent = txtTaxPercent.Text;
            string strVatAmount = lblAmountVat.Text;
            string strTaxAmount = txtAmountTax.Text;
            string strTaxRate = txtTaxRate.Text;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strUserID = Session["EmpSeq"].ToString();

            string strFromBankAcc = ddlFromBankAcc.SelectedValue;
            string strToBankAcc = ddlToBankAcc.SelectedValue;
            string strToConBankAcc = ddlToConBankAcc.SelectedValue;
            string strExcludeVat = lblExcludeVatAmount.Text;
            //DateTime? dtTaxInvoiceDate = dpTaxInvoiceDate.GetDateValue();
            //string strTaxInvoiceId = txtTaxInvoiceId.Text;

            DateTime dtNow = DateTime.Now;

            info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
            info.work_area_seq = Convert.ToInt32(string.IsNullOrEmpty(strWorkAreaSeq) ? "0" : strWorkAreaSeq);
            info.bgm_year = Convert.ToInt32(strBgmYear);
            info.event_seq = main.ConvertNullInt(strEventSeq);
            info.pay_name = strPayName;
            info.ref_no = strRefNo;
            info.pay_date = main.ConvertNullDateTime(strPayDate);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.petition_dtls_seq = main.ConvertNullInt(strPetitionDtlsSeq);
            info.amount = main.ConvertNullDouble(strAmount);
            info.vat = main.ConvertNullDouble(strVatAmount);
            info.tax = main.ConvertNullDouble(strTaxAmount);
            //info.vat_rate = main.ConvertNullDouble(strVatPercent);
            double excludeVat = (main.ConvertNullDouble(strExcludeVat) ?? 0);
            info.tax_rate = main.ConvertNullDouble(strTaxRate);
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            //info.tax_invoice_date = dtTaxInvoiceDate;
            //info.tax_invoice_id = strTaxInvoiceId;

            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = main.ConvertNullDateTime(dtNow);

            if (PanelTranfer.Visible)
            {
                if (ViewState["_tmpConId"] != null)
                    info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                else
                    info.to_bank_acc_id = main.ConvertNullInt(strToBankAcc);
                

                if (rblMethodSeq.SelectedIndex.Equals(2))
                    info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                else if (rblMethodSeq.SelectedIndex.Equals(3))
                    info.from_bank_acc_id = null;
            }

            string strPaySeq = pay.Insert(info);

            if (strEventSeq == "14" && !string.IsNullOrEmpty(lblReqRefNo.Text))
            {
                var deductions = !string.IsNullOrEmpty(lblReqRefNo.Text) ? 
                    prl.GetPayrollDeductions(null, null, lblReqRefNo.Text) 
                    : new List<M_FIM_PayrollDeduction>();
                foreach (var deduction in deductions)
                {
                    info.pay_name = deduction.title;
                    info.amount = (double?) deduction.amount;
                    info.contact_seq = deduction.ConId;
                    pay.Insert(info);
                }
            }

            if (PanelCheque.Visible)
            {
                foreach (GridDataItem item in grdCheque.Items)
                {
                    M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                    chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                    chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                    chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                    chequeInfo.record_status = "W";
                    chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chequeInfo.created_when = DateTime.Now;

                    paycheque.Insert(chequeInfo);

                    M_FIM_Cheques chq = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));
                    chq.cheque_date = main.ConvertNullDateTime(main.WebString(item["cheque_date"].Text));
                    chq.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chq.updated_when = DateTime.Now;
                    cheque.Update(chq);
                }
            }

            //foreach (GridDataItem item in grdMoneyRequestDtls.Items)
            //{
            //    var dtls = mrd.GetInfo(main.WebString(item["money_req_dtls_seq"].Text));
            //    dtls.percent_tax = ((RadNumericTextBox) item.FindControl("txtPercentTax")).Value;
            //    dtls.bath_amount_tax = ((RadNumericTextBox) item.FindControl("txtAmountTax")).Value;
            //    dtls.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            //    dtls.updated_when = DateTime.Now;

            //    mrd.Update(dtls);
            //}


            //PanelView.Visible = true;
            //PanelEdit1.Visible = false;
            //LoadRadGrid1();
            //RadGrid1.DataBind();
            //LoadRadGrid2();
            //RadGrid2.DataBind();
            main.MessageAlert(Page, "รหัสรายการคือ [" + strRefNo + "]");

            LoadData(strMoneyReqSeq, strPaySeq);

            PanelEdit1.Visible = true;
            PanelView.Visible = false;
            cmdInsert1.Visible = false;
            cmdUpdate1.Visible = true;
            cmdDelete1.Visible = true;
            //cmdCancel2.Visible = true;
            cmdAddNew.Visible = true;
            cmdApprove.Visible = true;
            cmdApprove.Enabled = true;
            cmdRealPay.Visible = false;
            PanelMessageSend.Visible = false;
            divControl1.Visible = true;
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            if (!CheckData1())
            {
                return;
            }

            M_FIM_Payments info = new M_FIM_Payments();

            string strPaySeq = lblPaySeq.Text;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = lblEventSeq.Text;
            string strPayName = txtPayName.Text;
            string strRefNo = lblPayRefNo.Text;
            //if (String.IsNullOrEmpty(lblPayRefNo.Text)) strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq);
            //else strRefNo = lblPayRefNo.Text;
            DateTime strPayDate = dpPayDate.GetDateValue().Value;
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strEmpSeq = (lblEmpSeq.Text.Length > 0 ? lblEmpSeq.Text : null);
            string strContactSeq = (lblContactSeq.Text.Length > 0 ? lblContactSeq.Text : null);
            string strContactPersonSeq = (lblContactPersonSeq.Text.Length > 0 ? lblContactPersonSeq.Text : null);
            string strPetitionSeq = (lblPetitionSeq.Text.Length > 0 ? lblPetitionSeq.Text : null);
            string strPetitionDtlsSeq = (lblPetitionDtlsSeq.Text.Length > 0 ? lblPetitionDtlsSeq.Text : null);
            string strAmount = lblPayAmount.Text; //(PanelPayrollDeduction.Visible ? lblPayAmountExcludeDeduction.Text : lblPayAmount.Text);
            //string strVatPercent = txtVatPercent.Text;
            //string strTaxPercent = txtTaxPercent.Text;
            string strVatAmount = lblAmountVat.Text;
            string strTaxAmount = txtAmountTax.Text;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strFromBankAcc = ddlFromBankAcc.SelectedValue;
            string strToBankAcc = ddlToBankAcc.SelectedValue;
            string strToConBankAcc = ddlToConBankAcc.SelectedValue;
            string strExcludeVat = lblExcludeVatAmount.Text;
            //DateTime? dtTaxInvoiceDate = dpTaxInvoiceDate.GetDateValue();
            //string strTaxInvoiceId = txtTaxInvoiceId.Text;

            string strUserID = Session["EmpSeq"].ToString();
            
            DateTime dtNow = DateTime.Now;

            info.pay_seq = Convert.ToInt32(strPaySeq);
            info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
            info.work_area_seq = Convert.ToInt32(string.IsNullOrEmpty(strWorkAreaSeq) ? "0" : strWorkAreaSeq);
            info.bgm_year = Convert.ToInt32(strBgmYear);
            info.event_seq = main.ConvertNullInt(strEventSeq);
            info.pay_name = strPayName;
            info.ref_no = strRefNo;
            info.pay_date = main.ConvertNullDateTime(strPayDate);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.petition_dtls_seq = main.ConvertNullInt(strPetitionDtlsSeq);
            info.amount = main.ConvertNullDouble(strAmount);
            info.vat = main.ConvertNullDouble(strVatAmount);
            info.tax = main.ConvertNullDouble(strTaxAmount);
            //info.vat_rate = main.ConvertNullDouble(strVatPercent);
            double excludeVat = (main.ConvertNullDouble(strExcludeVat) ?? 0);
            info.tax_rate = main.ConvertNullDouble(txtTaxRate.Text); ;
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            //info.tax_invoice_date = dtTaxInvoiceDate;
            //info.tax_invoice_id = strTaxInvoiceId;

            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = main.ConvertNullDateTime(dtNow);

            if (PanelTranfer.Visible)
            {
                if (ViewState["_tmpConId"] != null)
                    info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                else
                    info.to_bank_acc_id = main.ConvertNullInt(strToBankAcc);

                if (rblMethodSeq.SelectedIndex.Equals(2))
                    info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                else if (rblMethodSeq.SelectedIndex.Equals(3))
                    info.from_bank_acc_id = null;
            }

            pay.Update(info);

            if (PanelCheque.Visible)
            {
                foreach (GridDataItem item in grdCheque.Items)
                {
                    M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                    chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                    chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                    chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                    chequeInfo.record_status = "W";

                    if (main.WebString(item["pay_cheque_seq"].Text).Length == 0)
                    {
                        chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                        chequeInfo.created_when = DateTime.Now;
                        paycheque.Insert(chequeInfo);
                    }
                    else
                    {
                        chequeInfo.pay_cheque_seq = Convert.ToInt32(main.WebString(item["pay_cheque_seq"].Text));
                        chequeInfo.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                        chequeInfo.updated_when = DateTime.Now;
                        paycheque.Update(chequeInfo);
                    }

                    M_FIM_Cheques chq = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));
                    chq.cheque_date = main.ConvertNullDateTime(main.WebString(item["cheque_date"].Text));
                    chq.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chq.updated_when = DateTime.Now;
                    cheque.Update(chq);
                }
            }

            //foreach (GridDataItem item in grdMoneyRequestDtls.Items)
            //{
            //    var dtls = mrd.GetInfo(main.WebString(item["money_req_dtls_seq"].Text));
            //    dtls.percent_tax = ((RadNumericTextBox) item.FindControl("txtPercentTax")).Value;
            //    dtls.bath_amount_tax = ((RadNumericTextBox) item.FindControl("txtAmountTax")).Value;
            //    dtls.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            //    dtls.updated_when = DateTime.Now;

            //    mrd.Update(dtls);
            //}

            PanelView.Visible = true;
            PanelEdit1.Visible = false;
            LoadRadGrid1();
            RadGrid1.DataBind();
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            PanelEdit1.Visible = false;
            PanelView.Visible = true;
        }

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            Double? lstAmt = 0;
            Double? payAmt = 0;
            if (!String.IsNullOrEmpty(lblPayAmount.Text)) payAmt = Convert.ToDouble(lblPayAmount.Text);
            
            M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.cheque_date = dpChequeDate2.GetDateValue();
            info.record_status = "W";

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>) ViewState["Cheque"];
            listInfo.Add(info);
            if (listInfo.Count > 0)
            {
                for (int i = 0; i < listInfo.Count; i++)
                {
                    lstAmt += listInfo[i].amount;
                }
                if (lstAmt > payAmt)
                {
                    main.MessageAlert(Page, "พบข้อผิดพลาด! จำนวนเงินในเช็คมากกว่าจำนวนเงินจ่าย");
                    return;
                }
            }
            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
            lblPayChequeSeq.Text = "";
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>) ViewState["Cheque"];

            M_FIM_PaymentCheques info = listInfo[Convert.ToInt32(lblIndex.Text)];
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.cheque_date = dpChequeDate2.GetDateValue();
            info.record_status = "W";

            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdDelete2_Click(object sender, EventArgs e)
        {
            if (lblPayChequeSeq.Text.Length > 0)
            {
                M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
                info.pay_cheque_seq = Convert.ToInt32(lblPayChequeSeq.Text);
                info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.updated_when = DateTime.Now;
                paycheque.Delete(info);
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>) grdCheque.DataSource;
            listInfo.RemoveAt(Convert.ToInt32(lblIndex.Text));
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;

            if (RadGrid1.Visible)
            {
                LoadRadGrid1();
                RadGrid1.DataBind();
            }
            else if (RadGrid2.Visible)
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
            
            LoadDDLFromBankAccSeq();
        }

        protected void ddlFilterWorkAreaSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (RadGrid1.Visible)
            {
                LoadRadGrid1();
                RadGrid1.DataBind();
            }
            else if (RadGrid2.Visible)
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
        }

        protected void ddlFilterEventSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (RadGrid1.Visible)
            {
                LoadRadGrid1();
                RadGrid1.DataBind();
            }
            else if (RadGrid2.Visible)
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            lblBgmYear.Text = txtBgmYear.Text;
            if (RadGrid1.Visible)
            {
                LoadRadGrid1();
                RadGrid1.DataBind();
            }
            else if (RadGrid2.Visible)
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
        }

        //==========================================================================

        protected void cmdArival_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigBorder";
            cmdHistory.CssClass = "LinkButtonBigNoBorder";

            LoadRadGrid1();
            RadGrid1.DataBind();

            RadGrid1.Visible = true;
            RadGrid2.Visible = false;


            pnlMultiApprove1.Visible = false;
            SetVisibleCmdMultiActionSelectLink();
        }

        protected void cmdHistory_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigNoBorder";
            cmdHistory.CssClass = "LinkButtonBigBorder";

            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();

            RadGrid1.Visible = false;
            RadGrid2.Visible = true;

            pnlMultiApprove1.Visible = true;
            SetVisibleCmdMultiActionSelectLink();
        }

        protected void rblMethodSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblMethodSeq.SelectedIndex.Equals(0) || rblMethodSeq.SelectedIndex.Equals(1))
            {
                PanelTranfer.Visible = false;
                if (rblMethodSeq.SelectedIndex.Equals(1))
                {
                    PanelCheque.Visible = true;
                    LoadDDLBankAccSeq();
                }
                else PanelCheque.Visible = false;
                
            }
            else if (rblMethodSeq.SelectedIndex.Equals(2))
            {
                PanelTranfer.Visible = true;
                PanelCheque.Visible = false;
                if (ViewState["_tmpConId"] != null)
                {
                    int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                    LoadDDLToContactBankAccSeq(conid);
                    ddlToBankAcc.Visible = false;
                    ddlToConBankAcc.Visible = true;
                }
                else
                {
                    int? emp_seq = null;
                    if ((ViewState["_tmpEmpSeq"] != null) && ((ViewState["_tmpConId"] == null))) emp_seq = main.ConvertNullInt(ViewState["_tmpEmpSeq"].ToString());

                    LoadDDLToBankAccSeq(emp_seq);
                    ddlToBankAcc.Visible = true;
                    ddlToConBankAcc.Visible = false;
                }
                lblFromAcc.Visible = true;
                ddlFromBankAcc.Visible = true;
            }
            else if (rblMethodSeq.SelectedIndex.Equals(3))
            {
                PanelTranfer.Visible = true;
                PanelCheque.Visible = false;
                if (ViewState["_tmpConId"] != null)
                {
                    int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                    LoadDDLToContactBankAccSeq(conid);
                    ddlToBankAcc.Visible = false;
                    ddlToConBankAcc.Visible = true;
                }
                else
                {
                    int? emp_seq = null;
                    if ((ViewState["_tmpEmpSeq"] != null) && ((ViewState["_tmpConId"] == null))) emp_seq = main.ConvertNullInt(ViewState["_tmpEmpSeq"].ToString());

                    LoadDDLToBankAccSeq(emp_seq);
                    ddlToBankAcc.Visible = true;
                    ddlToConBankAcc.Visible = false;
                }
                lblFromAcc.Visible = false;
                ddlFromBankAcc.Visible = false;
            }
            else if (rblMethodSeq.SelectedIndex.Equals(4))
            {
                PanelTranfer.Visible = false;
                PanelCheque.Visible = false;
                lblFromAcc.Visible = false;
                ddlFromBankAcc.Visible = false;
            }
        }

        protected void ddlBankAccSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLChequeSeq();
        }

        protected void cmdApprove_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            LoadApprover();
            Page.SetFocus(cmdSave);
        }

        protected void LoadApprover()
        {
            cmdApprove.Visible = false;

            //if (lblRecordStatus.Text != "R")
            //{
                //cmdForword.Visible = true;
                //var pos_seq = send.GetPosSeqFromEmpSeq(Session["EmpSeq"].ToString());
                //DataTable dtb = send.GetCurrentApprover(pos_seq.ToString(), null, "FIM_PAYMENTS", 1);
                DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), null, "FIM_PAYMENTS", 1);

                if (dtb != null)
                {
                    if (dtb.Rows.Count > 0)
                    {
                        lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                        //ddlApprover.SelectedValue = dtb.Rows[0]["emp_seq"].ToString();
                        LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString(), dtb.Rows[0]["pos_seq"].ToString());
                    }
                }
            //}
            //else
            //{
            //    var model = send.GetInfoFromRefSeq(lblMoneyReqSeq.Text, "fim_money_requests");
            //    lblApprovePathSeq.Text = model.approve_path_seq.ToString();
            //    ddlApprover.SelectedValue = model.to_emp_seq.ToString();
            //    ddlApprover_SelectedIndexChanged(null, null);
            //}
        }

        protected void LoadEmpInfo(string strEmpSeq, string strPosSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                var model = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = model.emp_seq.ToString();
                lblPosSeq.Text = strPosSeq;
                ddlApprover.Text = model.emp_name;
                lblAppPosName.Text = model.pos_name + (strPosSeq != model.pos_seq.ToString() ? " (รักษาการณ์แทน " + GetPositionName(strPosSeq) + ")" : "");
                lblAppClassName.Text = model.class_name;
                lblAppExecPosName.Text = model.exec_pos_name;
                lblAppJobsiteName.Text = model.job_site_name;

                ddlApprover.Enabled = false;
            }
        }

        protected string GetPositionName(string strPosSeq)
        {
            dbManager.Open();
            DataTable dtb = null;

            try
            {
                dbManager.CreateParameters(1);
                dbManager.AddParameters(0, "@pos_seq", strPosSeq);

                string strSQL = "SELECT pos_name FROM hrm_mp_positions where pos_seq = @pos_seq";

                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                if (dtb.Rows.Count > 0)
                {
                    return dtb.Rows[0][0].ToString();
                }

                return "";
            }
            catch
            {
                return "";
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        protected void cmdRealPay_Click(object sender, EventArgs e)
        {
            PanelRealPay.Visible = true;
            txtReceiptNo.Text = "";
            txtReceiptName.Text = "";
            dpRealPayDate.SetValue(DateTime.Today);

            Page.SetFocus(cmdSave2);
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal) ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.GetFull(null, null, null);
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((M_HRM_PS_Employees) e.Item.DataItem).emp_name;
            e.Item.Value = ((M_HRM_PS_Employees) e.Item.DataItem).emp_seq.ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue);
        }

        protected void SetEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                M_HRM_PS_Employees info = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = info.emp_seq.ToString();
                lblPosSeq.Text = info.pos_seq.ToString();
                ddlApprover.Text = info.emp_name;
                lblAppPosName.Text = info.pos_name;
                lblAppClassName.Text = info.class_name;
                lblAppExecPosName.Text = info.exec_pos_name;
                lblAppJobsiteName.Text = info.working_job_site_name;
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (lblEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager) Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                //RadAjaxManager1.Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }

            try
            {
                string strPaySeq = lblPaySeq.Text;
                M_MessageSend info = new M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strPaySeq);
                info.ref_type = "fim_payments";
                info.ref_no = lblPayRefNo.Text;
                info.send_text = "ส่งขออนุมัติ " + txtPayName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.from_pos_seq = send.GetPosSeqFromEmpSeq("" + Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblEmpSeq.Text);
                info.to_pos_seq = main.ConvertNullInt(lblPosSeq.Text);//send.GetPosSeqFromEmpSeq(lblEmpSeq.Text);
                info.approve_path_seq = main.ConvertNullInt(lblApprovePathSeq.Text);
                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                M_FIM_Payments info2 = new M_FIM_Payments();
                info2.pay_seq = Convert.ToInt32(strPaySeq);
                info2.record_status = "P";
                info2.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info2.updated_when = DateTime.Now;
                pay.ChangeStatus(info2);
                cmdApprove.Enabled = false;
                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                PanelView.Visible = true;
                PanelEdit1.Visible = false;
                LoadRadGrid1();
                RadGrid1.DataBind();
                LoadRadGrid2();
                RadGrid2.DataBind();
                // RadGrid2AfterBind();
            }
            catch
            {
                main.MessageAlert(Page, "เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        public void UpdatePayCheckMultiple(int[] paySeqs)
        {
            main.MessageAlert(Page, "บันทึกการจ่ายเงินสำเร็จจำนวน " + "");
            // cheque.DoPayCheckMulti(paySeqs));
        }

        protected void cmdUpdate3_Click(object sender, EventArgs e)
        {
            M_FIM_Cheques info = new M_FIM_Cheques();
            string strChequeBookSeq = lblChequeBookSeq.Text;
            string strChequeSeq = lblChequeSeq.Text;
            string strBankAccSeq = lblBankAccSeq.Text;
            string strChequeNo = lblChequeNo.Text;
            string strPaydate = dpChequePayDate.GetStringValue();
            string strChequedate = dpChequeDate.GetStringValue();
            string strReceiver = txtReceiver.Text;
            string strRemarks = txtChequeRemarks.Text;
            string strChequeStatus = rblChequeStatus.SelectedValue;
            string strUserID = Session["EmpSeq"].ToString();
            Nullable<DateTime> dtActualPayDate = txtActualPayDate.GetDateValue();
            DateTime dtNow = DateTime.Now;

            /* 
            Comment Out by Raksakaew:เพราะต้องการย้ายขั้นตอนการ Post GL ไปไว้ขั้นตอนเมื่อได้รับการอนุมัติตาม requirement
            if (strChequeStatus == "3" && dtActualPayDate == null)
            {
                lblErrorActualPayDate.Text = "ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว";
                lblErrorActualPayDate.Visible = true;
                return;
            }
            else if ((strChequeStatus == "2" || strChequeStatus == "3") && dpChequePayDate == null)
            {
                lblErrorActualPayDate.Text = "ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว";
                lblErrorActualPayDate.Visible = true;
                return;
            }
            
            if (strChequeStatus == "3")
            {
                var modelCheque = cheque.GetInfo(strChequeSeq);
                var modelBankAccount = acc.GetInfo(modelCheque.bank_acc_seq.ToString());

                if (modelBankAccount.saving_bank_acc_seq != null)
                {
                    var models = transfer.GetFullFromCheque(strChequeSeq);
                    double SumAmount = main.ConvertNullDouble(paycheque.SumMoney(strChequeSeq)) ?? 0;

                    if (models.Count > 0)
                    {
                        if (models[0].tran_grp_seq != null)
                        {
                            lblErrorActualPayDate.Visible = true;
                            lblErrorActualPayDate.Text = "ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว";
                            return;
                        }
                        else
                        {
                            models[0].transfer_date = dtActualPayDate;
                            models[0].updated_by = main.ConvertNullInt(strUserID);
                            models[0].updated_when = dtNow;

                            transfer.Update(models[0]);
                        }
                    }
                    else
                    {
                        var model = new M_FIM_Transfers();

                        model.bgm_source_seq = main.ConvertNullInt(ddlFilterBgmSourceSeq.SelectedValue) ?? 0;
                        model.work_area_seq = 0;
                        model.bgm_year = main.ConvertNullInt(txtBgmYear.Text) ?? 0;
                        model.transfer_type = "3";
                        model.transfer_name = "โอนอัตโนมัติจากการจ่ายเช็ค " + strChequeNo;
                        model.ref_no = "auto transection";
                        model.ref_no_outside = null;
                        model.transfer_date = dtActualPayDate;
                        model.from_bank_acc_seq = modelCheque.bank_acc_seq;
                        model.to_bank_acc_seq = modelBankAccount.saving_bank_acc_seq;
                        model.bank_acc_type_seq = 1;
                        model.amount = SumAmount;
                        model.emp_seq = main.ConvertNullInt(strUserID);
                        model.tran_grp_seq = null;
                        model.record_status = "A";
                        model.created_by = main.ConvertNullInt(strUserID);
                        model.created_when = dtNow;
                        model.cheque_seq = Convert.ToInt32(strChequeSeq);

                        transfer.Insert(model);
                    }
                }
            }
            */

            if (strChequeStatus == "2" && main.ConvertNullDateTime(strPaydate) == null)
            {
                main.MessageAlert(Page, "กรณากรอก วันที่จ่ายเช็ค");
                lblErrorPayDate.Visible = true;
                return;
            }

            if (strChequeStatus == "3" && dtActualPayDate == null)
            {
                main.MessageAlert(Page, "กรณากรอก ขึ้นงินเมื่อวันที่");
                lblErrorActualPayDate.Visible = true;
                return;
            }

            lblErrorPayDate.Visible = false;
            lblErrorActualPayDate.Visible = false;

            info.cheque_seq = Convert.ToInt32(strChequeSeq);
            info.cheque_book_seq = main.ConvertNullInt(strChequeBookSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.cheque_no = main.ConvertNullInt(strChequeNo);
            info.pay_date = main.ConvertNullDateTime(strPaydate);
            info.cheque_date = main.ConvertNullDateTime(strChequedate);
            info.actual_pay_date = dtActualPayDate;
            info.receiver = strReceiver;
            info.remarks = strRemarks;
            info.cheque_status = strChequeStatus;
            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = dtNow;

            cheque.Update(info);

            if (info.pay_date.HasValue)
            {
                var model = new M_FIM_Payments();
                model.pay_seq = Convert.ToInt32(lblPaySeq.Text);
                model.real_pay_date = info.pay_date;
                model.receipt_no = null;
                model.receipt_name = null;
                model.updated_by = main.ConvertNullInt(strUserID);
                model.updated_when = dtNow;
                pay.UpdateReceipt(model);
            }

            if (info.pay_date.HasValue && (lblEventSeq.Text == "16" || lblEventSeq.Text == "18"))
            {
                mr.UpdateBorrowReturnDate(Convert.ToInt32(lblMoneyReqSeq.Text), info.pay_date.Value);
            }

            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
            PanelPayCheque.Visible = false;
        }

        protected void cmdCancel3_Click(object sender, EventArgs e)
        {
            lblChequeBookSeq.Text = "";
            lblChequeSeq.Text = "";
            lblBankAccSeq.Text = "";
            lblChequeNo.Text = "";
            dpChequePayDate.SetValue(null);
            dpChequeDate.SetValue(null);
            txtReceiver.Text = "";
            txtChequeRemarks.Text = "";
            //rblChequeStatus.SelectedValue = "";
            txtActualPayDate.SetValue(null);

            PanelPayCheque.Visible = false;
        }

        protected void rblChequeStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            liActualPayDate.Visible = rblChequeStatus.SelectedValue == "3";
        }

        protected void cmdSave2_Click(object sender, EventArgs e)
        {
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiptName = txtReceiptName.Text;
            DateTime? dtRealPayDate = dpRealPayDate.GetDateValue();

            if (dtRealPayDate == null)
            {
                lblErrorRealPayDate.Visible = true;
                return;
            }
            else
            {
                lblErrorRealPayDate.Visible = false;
            }


            if (lblEventSeq.Text == "31" || lblEventSeq.Text == "32" || lblEventSeq.Text == "34")
            {
                DAL.D_FIM_MoneyRequests mrr = new DAL.D_FIM_MoneyRequests();
                int x = Convert.ToInt32(lblMoneyReqSeq.Text);
                var modelMrr = mrr.GetInfo(x);
                int? BidderColId = modelMrr.bidder_col_Id;
                mrr.UpdateBidderCol(BidderColId);
            }

            var model = new M_FIM_Payments();
            model.pay_seq = Convert.ToInt32(lblPaySeq.Text);
            model.real_pay_date = dtRealPayDate;
            model.receipt_no = strReceiptNo;
            model.receipt_name = strReceiptName;
            model.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
            model.updated_when = main.ConvertNullDateTime(DateTime.Now);
            pay.UpdateReceipt(model);

            if (dtRealPayDate.HasValue && (lblEventSeq.Text == "16" || lblEventSeq.Text == "18"))
            {
                mr.UpdateBorrowReturnDate(Convert.ToInt32(lblMoneyReqSeq.Text), dtRealPayDate.Value);
            }

            PanelMessageSend.Visible = false;
            PanelRealPay.Visible = false;
            PanelView.Visible = true;
            PanelEdit1.Visible = false;
            LoadRadGrid1();
            RadGrid1.DataBind();
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                //GridDataItem item = (GridDataItem) e.Item;
                //var strStatus = item["record_status_name"].Text;
                //var strSeq = item["pay_seq"].Text;
                //var strContactSeq = item["contact_seq"].Text;
                //string strTax = item["tax"].Text;
                //LinkButton lbtnadd = (LinkButton) item["TemplateColumn1"].FindControl("cmdPrintPopup");
                //LinkButton lbtntax = (LinkButton) item["TemplateColumn2"].FindControl("cmdPrintPopupTax");
                //lbtnadd.Visible = false;

                //ปิดการซ่อนตาม requirement 28/03/2557
                //lbtntax.Visible = (main.ConvertNullDouble(strTax) ?? 0) > 0; //แก้ตาม requirement 2557/03/24

                //if (strStatus.StartsWith("จ่าย"))
                //{
                    //lbtnadd.Visible = true;

                    /*
                    lbtntax.Visible = (main.ConvertNullDouble(strTax) ?? 0) > 0; //แก้ตาม requirement 2557/03/24

                    if(!String.IsNullOrEmpty(strSeq)){
                        var lst = acm.GetListDetail(Convert.ToInt32(strSeq),"fim_payments");
                        if (lst.Count > 0)
                        {
                            lbtnadd.Visible = true;

                            if (String.IsNullOrEmpty(strContactSeq))
                                return;
                            if (lst.Count(w => w.account_name.Contains("ภงด")) > 0)
                            {
                                string doc_type = string.Empty;
                                if (lst.Where(s => s.account_seq == 2891).Any())
                                    doc_type = "pnd3";
                                else if (lst.Where(s => s.account_seq == 2890).Any())
                                    doc_type = "pnd53";
                                else
                                    return;

                                lbtntax.Visible = true;
                                //M_FIM_PaymentRecordPrints prp = pay.GetPNDPrintInfo(Convert.ToInt32(strSeq), doc_type);
                                //if (prp != null)
                                //{
                                //    if(prp.id > 0)
                                //        lbtntax.Visible = false;
                                //    else
                                //        lbtntax.Visible = true;
                                //}
                            }
                        }
                    }
                    */
                //}               
            }
        }

        //protected void txtVatPercent_TextChanged(object sender, EventArgs e)
        //{
        //    CalculatePercentChange();
        //}

        //protected void txtVatAmount_TextChanged(object sender, EventArgs e)
        //{
        //    CalculateAmountVatChange();
        //}

        //protected void txtTaxPercent_TextChanged(object sender, EventArgs e)
        //{
        //    CalculatePercentChange();
        //}

        //protected void txtTaxAmount_TextChanged(object sender, EventArgs e)
        //{
        //    CalculateAmountTaxChange();
        //}

        //protected void CalculateAmountVatChange()
        //{
        //    #region PrepareData 
        //    decimal dAmount = 0;
        //    decimal dVatAmount = 0;  
        //    decimal dIncludeVatAmount = 0; // จำนวนเงินที่ขอรวมVat 
        //    if (!decimal.TryParse(lblReqBathAmount.Text, out dIncludeVatAmount))  return; 
        //    if (!decimal.TryParse(txtVatAmount.Text, out dVatAmount)) dVatAmount = 0;  
        //    #endregion

        //    dAmount = dIncludeVatAmount - dVatAmount;
        //    lblExcludeVatAmount.Text = dAmount.ToString("#,##0.00"); 
        //}
        //protected void CalculateAmountTaxChange()
        //{
        //    #region PrepareData 
        //    decimal dAmount = 0;
        //    decimal dTaxAmount = 0;  // Tax ภาษีหักณที่จ่าย
        //    decimal dIncludeVatAmount = 0; // จำนวนเงินที่ขอรวมVat 
        //    if (!decimal.TryParse(lblReqBathAmount.Text, out dIncludeVatAmount))  return; 
        //    if (!decimal.TryParse(txtTaxAmount.Text, out dTaxAmount)) dTaxAmount = 0;  
        //    #endregion

        //    dAmount = dIncludeVatAmount - dTaxAmount;
        //    lblPayAmount.Text = dAmount.ToString("#,##0.00"); 
        //}

        //protected void CalculatePercentChange()
        //{
        //    #region PrepareData
        //    decimal dAmount = 0;
        //    decimal dVatPercent = 0; // Vat ภาษีมูลค่าเพิ่ม(%) 
        //    decimal dTaxPercent = 0; // Tax ภาษีหักณที่จ่าย(%) 
        //    decimal dVatAmount = 0;  // Vat ภาษีมูลค่าเพิ่ม
        //    decimal dTaxAmount = 0;  // Tax ภาษีหักณที่จ่าย
        //    decimal dIncludeVatAmount = 0; // จำนวนเงินที่ขอรวมVat
        //    decimal dExcludeVatAmount = 0; // จำนวนเงินที่ขอถอดVat
        //    if (!decimal.TryParse(lblReqBathAmount.Text, out dIncludeVatAmount))  return; 
        //    if (!decimal.TryParse(txtVatPercent.Text, out dVatPercent)) dVatPercent = 0; 
        //    if (!decimal.TryParse(txtTaxPercent.Text, out dTaxPercent)) dTaxPercent = 0; 
        //    #endregion

        //    #region หา จำนวนเงินที่ขอถอดVat
        //    // จำนวนเงินที่ขอถอดVat = จำนวนเงินที่ขอเช่น 10000 * (100 / 107) = 9345.7943
        //    dExcludeVatAmount = dIncludeVatAmount * (100 / (100 + dVatPercent));
        //    //            array[0] = 9345, array[1] = 7943
        //    string[] strPre = dExcludeVatAmount.ToString().Split('.'); 

        //    // เอาทศนิยม 2 ตำแหน่ง ตัดทศนิยมที่ 3 ขึ้นไปออก โดยไม่ปัดขึ้น
        //    if (strPre.Length > 0 && strPre[1].Length > 2)
        //    {
        //        strPre[1] = strPre[1].Substring(0, 2);
        //        dExcludeVatAmount = Convert.ToDecimal(strPre[0] + "." + strPre[1]);
        //    }
        //    #endregion

        //    #region หา จำนวน Vat
        //    // จำนวนVat = จำนวนเงินรวมVat - จำนวนเงินถอดVat
        //    dVatAmount = dIncludeVatAmount - dExcludeVatAmount;
        //    #endregion

        //    dTaxAmount = dExcludeVatAmount * dTaxPercent / 100;
        //    dAmount = dIncludeVatAmount - dTaxAmount;

        //    txtVatAmount.Text = dVatAmount.ToString("#,##0.00");
        //    txtTaxAmount.Text = dTaxAmount.ToString("#,##0.00");
        //    lblPayAmount.Text = dAmount.ToString("#,##0.00");
        //    lblExcludeVatAmount.Text = dExcludeVatAmount.ToString("#,##0.00");
        //}

        /* // Original
        protected void CalculatePercentToAmountTax()
        {
            decimal dAmount = 0;
            decimal dVatPercent = 0;
            decimal dTaxPercent = 0;
            decimal dVatAmount = 0;
            decimal dTaxAmount = 0;
            decimal dIncludeVatAmount = 0;
            decimal dExcludeVatAmount = 0;

            if (!decimal.TryParse(lblReqBathAmount.Text, out dIncludeVatAmount))
            {
                return;
            }

            if (!decimal.TryParse(txtVatPercent.Text, out dVatPercent))
            {
                dVatPercent = 0;
            }

            if (!decimal.TryParse(txtTaxPercent.Text, out dTaxPercent))
            {
                dTaxPercent = 0;
            }
            //decimal.TryParse(txtTaxPercent.Text, out dTaxPercent);

            decimal dPre = dIncludeVatAmount * (100 / (100 + dVatPercent));
            string[] strPre = dPre.ToString().Split('.');

            if (strPre.Length > 0 && strPre[1].Length > 2)
            {
                strPre[1] = strPre[1].Substring(0, 2);
                dPre = Convert.ToDecimal(strPre[0] + "." + strPre[1]);
            }

            dExcludeVatAmount = dPre;
            dVatAmount = dIncludeVatAmount - dExcludeVatAmount;
            dTaxAmount = dExcludeVatAmount * dTaxPercent / 100;
            dAmount = dIncludeVatAmount - dTaxAmount;

            txtVatAmount.Text = dVatAmount.ToString("#,##0.00");
            txtTaxAmount.Text = dTaxAmount.ToString("#,##0.00");
            lblPayAmount.Text = dAmount.ToString("#,##0.00");
            lblExcludeVatAmount.Text = dExcludeVatAmount.ToString("#,##0.00");
        }*/


        // Ekkachai: Move method to D_Fim_Checques.cs (call by update cheques)
        //protected void postFimTranfers(string paySeq, string bgmSourceSeq, string bgmYear)
        //{
        //    IBLL_FIM_PaymentCheques paycheque = new B_FIM_PaymentCheques();
        //    IList<M_FIM_PaymentCheques> paycheq = paycheque.GetFull(paySeq, null);

        //    IBLL_FIM_Cheques cheque = new B_FIM_Cheques();
        //    //ใส่ index เป็น 0 เพราะมีรายการเช็คเพียงรายการเดียวตาม Bizz. Rule
        //    M_FIM_Cheques cheq = cheque.GetInfo(paycheq[0].cheque_seq.ToString());

        //    string strChequeBookSeq = cheq.cheque_book_seq.ToString();
        //    string strChequeSeq = cheq.cheque_seq.ToString();
        //    string strBankAccSeq = cheq.bank_acc_seq.ToString();
        //    string strChequeNo = cheq.cheque_no.ToString();
        //    string strPaydate = cheq.pay_date.ToString();
        //    string strChequedate = cheq.cheque_date.ToString();
        //    string strReceiver = cheq.receiver;
        //    string strRemarks = cheq.remarks;
        //    string strChequeStatus = cheq.cheque_status;
        //    string strUserID = Session["EmpSeq"].ToString();
        //    Nullable<DateTime> dtActualPayDate = cheq.actual_pay_date;
        //    DateTime dtNow = DateTime.Now;
        //    IBLL_FIM_Transfers transfer = new B_FIM_Transfers();
        //    IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();

        //    if (strChequeStatus == "3" && dtActualPayDate == null)
        //    {
        //        //ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว จึงรีเทิร์นกลับ                
        //        return;
        //    }
        //    else if ((strChequeStatus == "2" || strChequeStatus == "3") && cheq.pay_date == null)
        //    {
        //        //ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว จึงรีเทิร์นกลับ
        //        return;
        //    }

        //    if (strChequeStatus == "3")
        //    {
        //        var modelCheque = cheque.GetInfo(strChequeSeq);
        //        var modelBankAccount = acc.GetInfo(modelCheque.bank_acc_seq.ToString());

        //        if (modelBankAccount.saving_bank_acc_seq != null)
        //        {
        //            var models = transfer.GetFullFromCheque(strChequeSeq);
        //            double SumAmount = main.ConvertNullDouble(paycheque.SumMoney(strChequeSeq)) ?? 0;

        //            if (models.Count > 0)
        //            {
        //                if (models[0].tran_grp_seq == null)
        //                {
        //                    models[0].transfer_date = dtActualPayDate;
        //                    models[0].updated_by = main.ConvertNullInt(strUserID);
        //                    models[0].updated_when = dtNow;

        //                    transfer.Update(models[0]);
        //                }
        //                else
        //                {
        //                    //ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากลงบัญชีแล้ว จึงรีเทิร์นกลับ
        //                    return;
        //                }
        //            }
        //            else
        //            {
        //                var model = new M_FIM_Transfers();

        //                model.bgm_source_seq = main.ConvertNullInt(bgmSourceSeq) ?? 0;
        //                model.work_area_seq = 0;
        //                model.bgm_year = main.ConvertNullInt(bgmYear) ?? 0;
        //                model.transfer_type = "3";
        //                model.transfer_name = "โอนอัตโนมัติจากการจ่ายเช็ค " + strChequeNo;
        //                model.ref_no = "auto transection";
        //                model.ref_no_outside = null;
        //                model.transfer_date = dtActualPayDate;
        //                model.from_bank_acc_seq = modelCheque.bank_acc_seq;
        //                model.to_bank_acc_seq = modelBankAccount.saving_bank_acc_seq;
        //                model.bank_acc_type_seq = 1;
        //                model.amount = SumAmount;
        //                model.emp_seq = main.ConvertNullInt(strUserID);
        //                model.tran_grp_seq = null;
        //                model.record_status = "A";
        //                model.created_by = main.ConvertNullInt(strUserID);
        //                model.created_when = dtNow;
        //                model.cheque_seq = Convert.ToInt32(strChequeSeq);

        //                transfer.Insert(model);
        //            }
        //        }
        //    }
        //}

        protected void grdMoneyRequestDtls_ItemCommand(object sender, GridCommandEventArgs e)
        {

        }

        protected void grdMoneyRequestDtls_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }

        protected void txtPercentTax_TextChanged(object sender, EventArgs e)
        {
            var dPercentTax = txtTaxRate.Value ?? 0;
            var dExcludeVatAmount = main.ConvertNullDouble(lblExcludeVatAmount.Text) ?? 0;
            var dTax = dExcludeVatAmount * dPercentTax / 100;

            txtAmountTax.Text = dTax.ToString();
            UpdateTotal();
        }

        protected void txtAmountTax_TextChanged(object sender, EventArgs e)
        {
            var dAmountTax = txtAmountTax.Value ?? 0;
            UpdateTotal();
        }

        protected void UpdateTotal()
        {
            double dAmount = (main.ConvertNullDouble(lblExcludeVatAmount.Text) ?? 0) + (main.ConvertNullDouble(lblAmountVat.Text) ?? 0);
            double dAmountTax = txtAmountTax.Value ?? 0;
            double dAmountPenalty = main.ConvertNullDouble(lblPenalty.Text) ?? 0;
            double dTotal = dAmount - dAmountTax - dAmountPenalty;

            lblPayAmount.Text = dTotal.ToString("#,##0.00");
        }

        //protected void CalAmountTax(RadNumericTextBox txtPercentTax, RadNumericTextBox txtAmountTax, GridDataItem item, int nStep)
        //{
        //    var dAmount = main.ConvertNullDouble(main.WebString(item["amount"].Text)) ?? 0;
        //    var dExcludeVat = main.ConvertNullDouble(main.WebString(item["exclude_vat"].Text)) ?? 0;
        //    var dPercentTax = txtPercentTax.Value ?? 0;
        //    var dAmountTax = txtAmountTax.Value ?? 0;

        //    if (nStep == 1)
        //    {
        //        dAmountTax = Math.Round(dExcludeVat*dPercentTax/100, 2);
        //    }

        //    txtAmountTax.Text = dAmountTax.ToString("#,##0.00");
        //    SumAmount();
        //}

        protected void SumAmount()
        {
            double dAmount = 0;
            double dAmountVat = 0;
            double dExcludeVat = 0;
            //double dAmountTax = 0;
            double dPenalty = 0;
            double dTotal = 0;

            foreach (GridDataItem item in grdMoneyRequestDtls.Items)
            {
                dAmount += main.ConvertNullDouble(main.WebString(item["amount"].Text)) ?? 0;
                dAmountVat += main.ConvertNullDouble(main.WebString(item["amount_vat"].Text)) ?? 0;
                dExcludeVat += main.ConvertNullDouble(main.WebString(item["exclude_vat"].Text)) ?? 0;
                //dAmountTax += ((RadNumericTextBox)item.FindControl("txtAmountTax")).Value ?? 0;
                dPenalty += main.ConvertNullDouble(main.WebString(item["penalty_amount"].Text)) ?? 0;

            }

            dTotal = dAmount - dPenalty;

            //lblAmountTax.Text = dAmountTax.ToString("#,##0.00");
            lblAmountVat.Text = dAmountVat.ToString("#,##0.00");
            lblExcludeVatAmount.Text = dExcludeVat.ToString("#,##0.00");
            lblPenalty.Text = dPenalty.ToString("#,##0.00");
            lblPayAmount.Text = dTotal.ToString("#,##0.00");
        }

        private void SetVisibleCmdMultiActionSelectLink(string command = "StopMultiAction")
        {
            cmdMultiSelectStart.Visible = command == "StopMultiAction" && RadGrid2.Visible;
            cmdMultiSelectStop.Visible = command == "StartMultiAction" && RadGrid2.Visible;
            cmdApproveConfirmPopup.Visible = command == "StartMultiAction" && RadGrid2.Visible;
            tbReasons.Visible = command == "StartMultiAction" && RadGrid2.Visible;
            RadGrid2.MasterTableView.GetColumn("action_select").Visible = command == "StartMultiAction";
            RadGrid2.AllowMultiRowSelection = command == "StartMultiAction";
            RadGrid2.ClientSettings.EnablePostBackOnRowClick = command != "StartMultiAction";
            RadGrid2.ClientSettings.Selecting.EnableDragToSelectRows = command == "StartMultiAction";
            RadGrid2.ClientSettings.Selecting.AllowRowSelect = true; //= command == "StartMultiAction";
            if (command == "StopMultiAction")
            {
                RadGrid2.PageSize = 10;
                RadGrid2.CssClass = "";
            }
            else
            {
                RadGrid2.PageSize = 100;
                RadGrid2.CssClass = "MyGridClass";
            }
        }

        protected void cmd_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandArgument.ToString().EndsWith("MultiAction"))
            {
                pnlMultiApprove1.Visible = true;
                SetVisibleCmdMultiActionSelectLink(e.CommandArgument.ToString());

                cmdArival.CssClass = "LinkButtonBigNoBorder";
                cmdHistory.CssClass = "LinkButtonBigBorder";

                LoadRadGrid2();
                RadGrid2.DataBind();
                // RadGrid2AfterBind();

                RadGrid1.Visible = false;
                RadGrid2.Visible = true;

            }
            else if (e.CommandArgument.ToString() == "ApproveConfirmPopup")
            {
                var item = (from GridDataItem gi in RadGrid2.SelectedItems
                    select Convert.ToInt32(gi.KeyValues.Split('"')[1])/* {send_seq:"16570"} */).ToList();
                var mrSeqs = (from i in item select Convert.ToInt32(i)).ToArray();
                int chequeAmount;
                int amount = cheque.DoPayCheckMulti(mrSeqs, DateTime.Now, DateTime.Now, 2, 
                    new SsMng().EmpSeqI, txtRemark.Text, out chequeAmount);

                main.MessageAlert(Page, "ท่านได้ทำการบันทึกการจ่ายเงินจำนวน " + amount + " รายการ");

                LoadRadGrid2();
                RadGrid2.DataBind();
            }
        }

        protected void cmdReject_Click(object sender, EventArgs e)
        {
            int nEmpSeq = main.ConvertNullInt(Session["EmpSeq"].ToString()) ?? 0;
            string strError = "";

            if (lblPaySeq.Text.Length > 0)
            {
                int nPaySeq = Convert.ToInt32(lblPaySeq.Text);

                if (!acm2.RollbackPayment(nPaySeq, nEmpSeq, out strError))
                {
                    main.MessageAlert(Page, strError);
                    return;
                }

                M_FIM_Payments info = new M_FIM_Payments();
                info.pay_seq = Convert.ToInt32(lblPaySeq.Text);
                info.updated_by = nEmpSeq;
                info.updated_when = DateTime.Now;

                pay.Delete(info);

                PanelEdit1.Visible = false;
                PanelView.Visible = true;
                LoadRadGrid2();
                RadGrid2.DataBind();
            }

            int nMoneyReqSeq = Convert.ToInt32(lblMoneyReqSeq.Text);
            acm2.RollbackMoneyReq(nMoneyReqSeq, nEmpSeq, out strError);

            main.MessageAlert(Page, strError);
        }
    }
}
